package cn.lzy.profile;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Profiles;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;

import java.util.List;

/**
 * @Description MyProfile注解的条件
 * @Author lzy
 * @Date 2023/11/29 16:35
 * @Version
 **/
public class MyProfileCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // 获取 @MyProfile的属性键值对（key-属性名，value-属性的值）
        MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(MyProfile.class.getName());
        if (attrs != null) {
            // 获取属性值 value 的值
            List<Object> list = attrs.get("value");
            for (Object value : list) {
                boolean flag = context.getEnvironment().acceptsProfiles(Profiles.of((String[]) value));
                if (flag) {
                    return true;
                }
            }
        }
        return false;
    }
}
